package com.zzb.weixin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzb.util.HTTPUtil;
import com.zzb.weixin.WeiXinUtil;
import com.zzb.weixin.constant.WXUrlName;
import com.zzb.weixin.exception.WeiXinException;
import com.zzb.weixin.json.JsonArray;
import com.zzb.weixin.json.JsonObject;
import com.zzb.weixin.listener.DefaultHandleMessageListener;
import com.zzb.weixin.listener.DefaultListenerManager;
import com.zzb.weixin.model.event.EventMsg;
import com.zzb.weixin.model.msg.basic.ImageMsg;
import com.zzb.weixin.model.msg.basic.ImageTextData;
import com.zzb.weixin.model.msg.basic.ImageTextMsg;
import com.zzb.weixin.model.msg.basic.TextMsg;
import com.zzb.weixin.model.msg.basic.VoiceMsg;
import com.zzb.weixin.org.json.JSONArray;
import com.zzb.weixin.org.json.JSONException;

/**
 * 处理微信服务器请求的Servlet URL地址：http://xxx/weixin/dealwith.do
 * 
 * 注意：官方文档限制使用80端口哦！
 * 
 */
public class WinXinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	//TOKEN 是你在微信平台开发模式中设置的哦
	public static final String TOKEN = "3nwk9AihFYMMClSB";



	/**
	 * 处理微信服务器验证
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String signature = request.getParameter(WXUrlName.SIGNATURE);// 微信加密签名
		String timestamp = request.getParameter(WXUrlName.TIME_STAMP);// 时间戳
		String nonce = request.getParameter(WXUrlName.NONCE);// 随机数
		String echostr = request.getParameter(WXUrlName.ECHO_STR);// 随机字符串
		System.out.println(timestamp+nonce+signature);
		Writer out = response.getWriter();
		if (WeiXinUtil.check(TOKEN, timestamp, nonce, signature)) {
			out.write(echostr);// 请求验证成功，返回随机码
		} else {
			out.write("");
		}
		out.flush();
		out.close();
	}





	/**
	 * 处理微信服务器发过来的各种消息，包括：文本、图片、地理位置、音乐等等
	 * 
	 * 
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			//处理微信消息
			listenerManger.process(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		listenerManger.close();//关闭Session
	}

	//以下代码为处理微信接收的消息并自动返回指定内容的代码，具体实现内容可自行修改
	private static DefaultListenerManager listenerManger = DefaultListenerManager
			.newInstance();
	static {
		//向监听器中添加事件响应方法，可以添加多个，会遍历执行
		listenerManger.addOnHandleMessageListener(new DefaultHandleMessageListener() {

			@Override
			public boolean onMsg(VoiceMsg msg) {
				TextMsg reMsg = new TextMsg();
				reMsg.setFromUserName(msg.getToUserName());
				reMsg.setToUserName(msg.getFromUserName());
				reMsg.setCreateTime(msg.getCreateTime());
				reMsg.setContent("识别结果: " + msg.getRecognition());
				listenerManger.callback(reMsg);// 回传消息
				return true;
			}


			@Override
			public boolean onMsg(TextMsg msg) {
				if ("1".equals(msg.getContent())) {// 菜单选项1
					System.out.println(msg.getFromUserName());
					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());
					reMsg.setContent("【菜单】\n" + "1. 功能菜单\n" + "2. 图文消息测试\n"
							+ "3. 图片消息测试\n");
					System.out.println(msg.getFromUserName());
					listenerManger.callback(reMsg);// 回传消息
				} else if ("2".equals(msg.getContent())) {
					// 回复一条消息
					ImageTextData d1 = new ImageTextData(
							"德国电动汽车项目寻找中国合作伙伴",
							"该车是VIP接送高档商务车，是德国汽车设计事务所约200人团队研发的属于第三代技术的电...",
							"http://www.chinamerger.com/chinamergerImage/1595/null20141020111050267aIZMUD8G.jpg",
							"http://m.chinamerger.com/recommend.html?projectid=1035#pagetwo");
					ImageTextData d2 = new ImageTextData(
							"德国电动汽车锂电池封装合作项目寻求中方合作伙伴",
							"一家奥地利公司开发了一项新封装实用专利，即提供电动汽车用电池的新方案&nbsp;",
							"http://www.chinamerger.com/chinamergerImage/1595/null2014101713573102538LGXWFx.JPG",
							"http://m.chinamerger.com/recommend.html?projectid=1033#pagetwo");

					ImageTextMsg mit = new ImageTextMsg();
					mit.setFromUserName(msg.getToUserName());
					mit.setToUserName(msg.getFromUserName());
					mit.setCreateTime(msg.getCreateTime());
					try {
						mit.addItem(d1);
						mit.addItem(d2);
					} catch (Exception e) {
						e.printStackTrace();
					}
					listenerManger.callback(mit);
				} else if ("3".equals(msg.getContent())) {
					ImageMsg rmsg = new ImageMsg();
					rmsg.setFromUserName(msg.getToUserName());
					rmsg.setToUserName(msg.getFromUserName());
					rmsg.setPicUrl("http://www.chinamerger.com/chinamergerImage/1595/null20141020111050267aIZMUD8G.jpg");
					listenerManger.callback(rmsg);
				} else if ("4".equals(msg.getContent())) {
					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());
					reMsg.setContent("<a href=\"http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MjM5MjczNjk1NQ==#wechat_webview_type=1&wechat_redirect\">查看历史消息</a>");
					System.out.println(msg.getFromUserName());
					listenerManger.callback(reMsg);// 回传消息
				} else {
					try {
						ImageTextMsg mit = new ImageTextMsg();
						mit.setFromUserName(msg.getToUserName());
						mit.setToUserName(msg.getFromUserName());
						mit.setCreateTime(msg.getCreateTime());
						InputStream in = new URL("http://192.168.1.33:8088/mw/website/searchAction!searchSaleBusiness.action?searchStr="+URLEncoder.encode(msg.getContent(), "UTF-8")).openStream();
						String str = HTTPUtil.getContext(in,"UTF-8");
						JsonArray ja = new JsonArray(new JSONArray(str));
						for (int i = 0; i < ja.length(); i++) {
							JsonObject jo = ja.getAsJsonObject(i);
							ImageTextData d1 = new ImageTextData(
									jo.getAsString("标题"),
									jo.getAsString("项目亮点"),
									"http://www.chinamerger.com/chinamergerImage/"+jo.getAsString("registerid")+"/"+jo.getAsString("附件名称"),
									"http://m.chinamerger.com/recommend.html?projectid="+jo.getAsString("_id")+"#pagetwo");
							mit.addItem(d1);
						}
						listenerManger.callback(mit);// 回传消息
						return true;
					} catch (WeiXinException e) {
						e.printStackTrace();
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return false;
				}
				return true;
			}

			@Override
			public boolean onMsg(EventMsg msg) {
				switch (msg.getEvent()) {
				case SUBSCRIBE:// 订阅
					System.out.println("关注人：" + msg.getFromUserName());
					System.out.println("参数值：" + msg.getEventKey());

					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());

					reMsg.setContent("【菜单】\n" + "1. 功能菜单\n" + "2. 图文消息测试\n"
							+ "3. 图片消息测试\n");

					listenerManger.callback(reMsg);// 回传消息
					return true;
				case UNSUBSCRIBE:// 取消订阅
					System.out.println("取消关注：" + msg.getFromUserName());
					return true;
				case CLICK:// 点击事件
					System.out.println("用户：" + msg.getFromUserName());
					System.out.println("点击Key：" + msg.getEventKey());
					try {
						ImageTextMsg mit = new ImageTextMsg();
						mit.setFromUserName(msg.getToUserName());
						mit.setToUserName(msg.getFromUserName());
						mit.setCreateTime(System.currentTimeMillis());
						/*InputStream in = new URL("http://www.chinamerger.com/webapp/getRecommendList.action?limit=10&start=0&page=1").openStream();
						String str = HTTPUtil.getContext(in,"UTF-8");
						System.out.println(str);
						JsonArray ja = new JsonArray(new JSONArray(str));
						for (int i = 0; i < ja.length(); i++) {
							JsonObject jo = ja.getAsJsonObject(i);
							ImageTextData d1 = new ImageTextData(
									jo.getAsString("caption"),
									jo.getAsString("lightspot"),
									jo.getAsString("imagename"),
									"http://m.chinamerger.com/recommend.html?projectid="+jo.getAsString("projectid")+"#pagetwo");
							mit.addItem(d1);
						}*/
						switch (msg.getEventKey()) {
						case "jidu":
							ImageTextData imageTextData = new ImageTextData(
									"晨哨网《2014年一季度中资海外投资并购报告》(上)",
									"晨哨网《2014年一季度中资海外投资并购报告》(上)",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKzmHYmTxNnN0E0CGL5m7yGjUxiaYia9teOUZpbibyEic1RowAIsq4DdVhxQ/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984217&idx=1&sn=225ba6ea6707fc9af7f6783a9faabb77#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"晨哨网《2014年一季度中资海外投资并购报告》(下)",
									"晨哨网《2014年一季度中资海外投资并购报告》(下)",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKzmHYmTxNnN0E0CGL5m7yGjUxiaYia9teOUZpbibyEic1RowAIsq4DdVhxQ/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984217&idx=2&sn=a7fd8ea8a2e429cda1373997b8b4c2d5#rd");
							mit.addItem(imageTextData);
							break;
						case "hangye":
							imageTextData = new ImageTextData(
									"晨哨发布《2014上半年中企海外房地产投资报告》",
									"晨哨发布《2014上半年中企海外房地产投资报告》",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKjDbRJG1lx5EMQyjFlxr7FTMP3d0viaBggwEljYReynXIZlibRdMoHYaA/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=1&sn=77e0531aaa0625e9013869c349f72774#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"【海外房地产投资半年报】中国企业海外房地产投资数据与趋势",
									"【海外房地产投资半年报】中国企业海外房地产投资数据与趋势",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKRxstsq1ow26ZnEickYRfINIxCvlFEUP7HbDsHw4lupObqwftaMbG7ng/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=2&sn=6aa76c86292db980a621d48fc58ae935#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"【海外房地产投资半年报】中企海外房地产投资法律政策变动",
									"【海外房地产投资半年报】中企海外房地产投资法律政策变动",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKK8BbaewmICibykDnvCX9F18AS0pIpWPgHAHLGoeR7dwCkZPM1Jb6VrA/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=3&sn=565c4a87bf526dcc2da7b8410464868a#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"【海外房地产投资半年报】运用房地产基金与信托投资海外分析",
									"【海外房地产投资半年报】运用房地产基金与信托投资海外分析",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKaz7DbsuRdaeE34ujhnZFXxV9yZZ0AmTavgnUymmhLUyMMLuoI06TicA/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=4&sn=9ebc04f4f5327adab1c72b821cb2ab6d#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"【海外房地产投资半年报】欧美房地产市场投资新趋势",
									"【海外房地产投资半年报】欧美房地产市场投资新趋势",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKWch0hibprqG14hAgVBTkG1mr8icfwnKicmaUyy0oVEPfIUvP6x1eSibERQ/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=5&sn=514d2ba903f44c16fc181cf3322c0077#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"【海外房地产投资半年报】海外酒店赌场投资分析",
									"【海外房地产投资半年报】海外酒店赌场投资分析",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKQraL9iclchLH7Jq7rCpMSqcsfu1zklweewjDmC5TnnjOSd9XlINT4pQ/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=6&sn=17019e548d279b09a083e96163689fb7#rd");
							mit.addItem(imageTextData);
							imageTextData = new ImageTextData(
									"《中国集成电路行业海外并购报告》",
									"《中国集成电路行业海外并购报告》",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib1fVgTGxVxQibdia7eMFrCCWKPYnZ3LQRJtcP2H6hU9pSKMEuvoWeDnYRL1fFdajLaq5Z542cQXzDPQ/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=200984618&idx=7&sn=f17c25263c12b526d9fc5146dbc0d85b#rd");
							mit.addItem(imageTextData);
							
							break;
						case "huodong":
							imageTextData = new ImageTextData(
									"【晨哨市场活动回顾】",
									"【晨哨市场活动回顾】",
									"https://mmbiz.qlogo.cn/mmbiz/Z6ziaPKBXvib3qDPoXrW8zUrlJahYA1BqgWcY30sTow2MzdbdJKExS2XHxibq2PmZWXEc6VI50iblw9L3DBIavKFcg/0",
									"http://mp.weixin.qq.com/s?__biz=MjM5MjczNjk1NQ==&mid=201449267&idx=1&sn=22f4fdb9a0d9de18c814bfb0533ffe79#rd");
							mit.addItem(imageTextData);
							break;

						default:
							break;
						}
						listenerManger.callback(mit);// 回传消息
						return true;
					} catch (WeiXinException e) {
						e.printStackTrace();
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				default:
					return false;
				}
			}
		});
	}

}
